package com.tadpole.music.view.activity.me.yun;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.provider.Settings;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.Nullable;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.entity.LocalMedia;
import com.luck.picture.lib.permissions.RxPermissions;
import com.tadpole.music.R;
import com.tadpole.music.iView.me.yun.YunSubmitIView;
import com.tadpole.music.presenter.me.yun.YunSubmitPresenter;
import com.tadpole.music.utils.Mutils;
import com.tadpole.music.utils.NoDoubleClickListener;
import com.tadpole.music.utils.PictureFileUtil;
import com.tadpole.music.utils.QiniuYunUtil;
import com.tadpole.music.utils.ToastUtils;
import com.tadpole.music.view.activity.base.BaseActivity;
import com.tadpole.music.view.widget.XCRoundRectImageView;
import com.tadpole.music.view.widget.YunOutPopup;

import java.io.File;
import java.util.List;

import io.reactivex.functions.Consumer;

/**
 * 蝌蚪云考试  乐器考试
 * Created By 孙岩
 * on 2021/2/9
 */
public class YunExaminationOneActivity extends BaseActivity implements YunSubmitIView {
    private static int REQUEST_CODE_OPEN_VIDEO = 0x01;
    //回退
    private View view_back_icon;
    //标题
    private TextView actionbar_title;
    //姓名
    private TextView tvName;
    //身份证号
    private TextView tvCardNumber;
    //上传类型
    private TextView tv;
    //上传
    private FrameLayout rlGo;
    //上传
    private TextView tvGo;
    //提交
    private TextView tvSubmit;

    //上传完成以后显示
    private FrameLayout fmShow;
    private RelativeLayout rlClick;
    //图片
    private XCRoundRectImageView imageVideo;
    //视频播放
    private ImageView ivStart;
    //删除
    private ImageView ivDeleteImg;

    //提交进度
    private LinearLayout ll_upload;
    //进度
    private ProgressBar mprogress;
    private TextView tv_upload;

    //提交图片image 还是 视频video
    private String type;
    //标题
    private String title;
    //姓名
    private String name;
    //身份证号
    private String card;

    //提交的数据源
    private String path = "";
    //上传中
    private boolean isUploading = false;

    //提交考试
    private YunSubmitPresenter yunSubmitPresenter;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_yun_examination_one);

        type = getIntent().getStringExtra("type");
        title = getIntent().getStringExtra("title");
        name = getIntent().getStringExtra("name");
        card = getIntent().getStringExtra("card");

        initViews();
        initListeners();

        yunSubmitPresenter = new YunSubmitPresenter();
        yunSubmitPresenter.attachView(this);
    }

    //初始化控件
    private void initViews() {
        view_back_icon = findViewById(R.id.view_back_icon);
        actionbar_title = findViewById(R.id.actionbar_title);
        tvName = findViewById(R.id.tvName);
        tvCardNumber = findViewById(R.id.tvCardNumber);
        tv = findViewById(R.id.tv);
        rlGo = findViewById(R.id.rlGo);
        tvGo = findViewById(R.id.tvGo);
        tvSubmit = findViewById(R.id.tvSubmit);
        fmShow = findViewById(R.id.fmShow);
        imageVideo = findViewById(R.id.imageVideo);
        ivStart = findViewById(R.id.ivStart);
        ivDeleteImg = findViewById(R.id.ivDeleteImg);
        ll_upload = findViewById(R.id.ll_upload);
        mprogress = findViewById(R.id.progress);
        tv_upload = findViewById(R.id.tv_upload);
        rlClick = findViewById(R.id.rlClick);

        if (type.equals("image")) {
            tv.setText("上传考试图片");
            tvSubmit.setText("上传图片");
        } else if (type.equals("video")) {
            tv.setText("上传考试视频");
            tvSubmit.setText("上传视频");
        }

        actionbar_title.setText(title);
        tvName.setText(name);
        tvCardNumber.setText(card);

    }

    //初始化监听器
    private void initListeners() {
        view_back_icon.setOnClickListener(new NoDoubleClickListener() {
            @Override
            protected void onNoDoubleClick(View v) {
                YunExaminationOneActivity.this.finish();
            }
        });

        //上传
        rlGo.setOnClickListener(new NoDoubleClickListener() {
            @Override
            protected void onNoDoubleClick(View v) {
                if (Mutils.isNetworkAvailable()) {
                    if (isUploading) {
                        ToastUtils.show("视频正在上传中，请耐心等待");
                    } else {
                        andPermission();
                    }
                } else {
                    ToastUtils.show(getResources().getString(R.string.net_work));
                }
            }
        });

        //上传
        tvGo.setOnClickListener(new NoDoubleClickListener() {
            @Override
            protected void onNoDoubleClick(View v) {
                if (Mutils.isNetworkAvailable()) {
                    if (isUploading) {
                        ToastUtils.show("视频正在上传中，请耐心等待");
                    } else {
                        andPermission();
                    }
                } else {
                    ToastUtils.show(getResources().getString(R.string.net_work));
                }
            }
        });

        //提交数据
        tvSubmit.setOnClickListener(new NoDoubleClickListener() {
            @Override
            protected void onNoDoubleClick(View v) {
                if(Mutils.isNetworkAvailable()){
                    if(path.equals("")){
                        ToastUtils.show("请上传作品");
                    }else{
                        yunSubmitPresenter.submit("","","",path);
                    }
                }else{
                    ToastUtils.show(getResources().getString(R.string.net_work));
                }
            }
        });
    }

    //权限
    @SuppressLint("CheckResult")
    private void andPermission() {
        RxPermissions rxPermission = new RxPermissions(this);
        rxPermission
                .request(
                        Manifest.permission.CAMERA,
                        Manifest.permission.WRITE_EXTERNAL_STORAGE,
                        Manifest.permission.READ_EXTERNAL_STORAGE
                ).subscribe(new Consumer<Boolean>() {
            @Override
            public void accept(Boolean aBoolean) throws Exception {
                //请求权限成功
                if (aBoolean) {
                    if(type.equals("video")){
                        PictureFileUtil.openGalleryVideo(YunExaminationOneActivity.this, REQUEST_CODE_OPEN_VIDEO);
                    }else if(type.equals("image")){
                        PictureFileUtil.openGalleryPicture(YunExaminationOneActivity.this, REQUEST_CODE_OPEN_VIDEO);
                    }
                } else {//失败
                    String msg = "请点击【去授权】打开相应权限！";
                    showAlert(msg);
                }
            }
        });
    }

    //授权
    public void showAlert(String msg) {
        new AlertDialog.Builder(this).setMessage(msg).
                setPositiveButton("去授权",
                        new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
                                Uri uri = Uri.fromParts("package", getApplicationContext().getPackageName(), null);
                                intent.setData(uri);
                                startActivity(intent);
                            }
                        }).setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        }).setCancelable(true).show();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK && requestCode == REQUEST_CODE_OPEN_VIDEO) {
            //视频回调
            List<LocalMedia> pictureList = PictureSelector.obtainMultipleResult(data);
            uploadAvatar(pictureList);
        }
    }

    //上传七牛
    private void uploadAvatar(final List<LocalMedia> pictureList) {
        ll_upload.setVisibility(View.VISIBLE);

        final QiniuYunUtil qiniuUploadMoreUtil = new QiniuYunUtil();
        qiniuUploadMoreUtil.upLoadFileToQiNiu(this, 0, 1, pictureList.get(0).getPath());
        qiniuUploadMoreUtil.setQiniuUtilI(new QiniuYunUtil.QiniuUtilI() {
            @Override
            public void succeed(boolean allok, int current, String qiNiuBackPicPath) {
                if (allok) {
                    tv_upload.setText("上传成功");
                    isUploading = false;
                    ll_upload.setVisibility(View.GONE);
                    fmShow.setVisibility(View.VISIBLE);
                    rlClick.setVisibility(View.GONE);

                    Glide.with(YunExaminationOneActivity.this).load(qiNiuBackPicPath).into(imageVideo);
                    path = qiNiuBackPicPath;

                    ivDeleteImg.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            if (isUploading) {
                                ToastUtils.show("视频上传中,请耐心登录");
                            } else {
                                tv_upload.setText("上传中");
                                rlClick.setVisibility(View.VISIBLE);
                                fmShow.setVisibility(View.GONE);
                                path = "";
                            }
                        }
                    });

                    ivStart.setOnClickListener(new NoDoubleClickListener() {
                        @Override
                        protected void onNoDoubleClick(View v) {

                            if (isUploading) {
                                ToastUtils.show("视频上传中,请耐心登录");
                            } else {
                                Intent intent = new Intent(YunExaminationOneActivity.this, FullVideoActivity.class);
                                intent.putExtra("label", path);
                                startActivity(intent);
                            }
                        }
                    });
                }
            }

            //七牛上传失败
            @Override
            public void failure() {
                isUploading = false;
                if (Mutils.isNetworkAvailable()) {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            tv_upload.setText("上传失败，请稍后再试");
                        }
                    });

                    ll_upload.setVisibility(View.VISIBLE);
                    mprogress.setVisibility(View.GONE);

                    Handler mHandler = new Handler();
                    Runnable r = new Runnable() {
                        @Override
                        public void run() {
                            ll_upload.setVisibility(View.GONE);
                            mprogress.setVisibility(View.VISIBLE);
                        }
                    };
                    mHandler.postDelayed(r, 2000);
                } else {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            ToastUtils.show("请检查网络状态");
                        }
                    });
                }
            }

            //七牛上传中
            @Override
            public void progress(int current, int progress) {
                mprogress.setProgress(progress);
                ll_upload.setVisibility(View.VISIBLE);
                isUploading = true;
                fmShow.setVisibility(View.VISIBLE);
            }
        });
    }

    @Override
    public void showYunSubmit() {
        showFinishResult();
    }

    //答题结束 弹窗
    private void showFinishResult(){
        final YunOutPopup yunOutPopup = new YunOutPopup(YunExaminationOneActivity.this);
        yunOutPopup.setPopupWindowFullScreen(true);
        yunOutPopup.setDismissWhenTouchOutside(false);

        yunOutPopup.showPopupWindow();
        yunOutPopup.setModeListener(new YunOutPopup.IModeSelection() {
            @Override
            public void getMode(int mode) {
                if (mode == 1) {//确定
                    yunOutPopup.dismiss();
                    setResult(1024);
                    YunExaminationOneActivity.this.finish();
                }
            }
        });
    }
}
